package com.ttc.mBackup.BackupAgent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;

import com.dropbox.client.DropboxAPI;
import com.dropbox.client.DropboxAPI.Entry;

import com.ttc.mBackup.BackupActivity;
import com.ttc.mBackup.R;
import com.ttc.mBackup.BackupAgent.DBAdapter;
import com.ttc.mBackup.BackupAgent.DropBoxPerform;
import com.ttc.mBackup.BackupAgent.LoginAsyncTask;
import com.ttc.mBackup.BackupAgent.LoginDropbox;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PerformTask extends Activity{

	/*
	 * Define Widget 
	 * */
	TextView title;
	ImageView taskImg;
	ListView listtask;
	Button cont,cancel;
	ProgressBar progress;
	private DBAdapter db;
	/*Create to Perform Thread and Rotation*/
	private AsyncProcess asyncthread;
	private	PerformTask activity;
	
	/*Adapter and model*/
	ArrayAdapter<String> adapter;
	ArrayList<String> model= new ArrayList<String>();
	ArrayList<String> listSys= new ArrayList<String>();
	/*create DropboxAPI*/
	boolean checker;
	private DropboxAPI api;
	/*Save File and Dir of file*/
	private String _Dir;
	private String _Name;
	private boolean _Cloud;
	
	

/*Create Object of DropBoxPerform class*/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.progresslayout);
		/*Get ID for Widget*/
		cont = (Button) findViewById(R.id.Cont_btn);
		cancel = (Button) findViewById(R.id.Cancle_btn);
		listtask = (ListView) findViewById(R.id.task_list);
		taskImg = (ImageView) findViewById(R.id.image_done);
		title = (TextView) findViewById(R.id.task_label);
		progress = (ProgressBar) findViewById(R.id.PBar);
		
		/*Get Last Task*/
		asyncthread = (AsyncProcess) getLastNonConfigurationInstance();
		
		/*Check Finish Task*/
		 checker = getIntent().getBooleanExtra("DONE",false );
		if(checker)
		{
			
		LinearLayout line = (LinearLayout) findViewById(R.id.laylinear);
		line.setVisibility(2);
		
		cancel.setText("Done");
		cancel.setVisibility(0);
		title.setText("Your Task Has Done Already ");
		progress.setVisibility(8);
		taskImg.setVisibility(0);
		listtask.setVisibility(8);}
	
		else{

		title.setVisibility(8);		
		progress.setVisibility(0);
		progress.setProgress(0);
		View viewline =findViewById(R.id.viewline);
		viewline.setVisibility(8);
		
		/*Get Extras*/
		Bundle extras = getIntent().getExtras();
		if(extras!=null){
		/*Database Contructor*/
			db = new DBAdapter(getApplicationContext());
			listSys = extras.getStringArrayList(BARSelector.KEY_ELEMENT_SYSTEM);
			/*Save dir string and name string for taskt*/
			_Dir =extras.getString(BARLocaltion.DIR_CHOICE);
			_Name = extras.getString("FILE_NAME");
			_Cloud=extras.getBoolean(BARLocaltion.CLOUD_STORE);
			/*
			 *  Create Adapter for listview and setChoiceMode
			 *  
			 * */
		adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked,model);
		listtask.setChoiceMode(2);
		listtask.setAdapter(adapter);
		if(asyncthread==null){
		/*Progress Task : Backup or Resotre despend on boolean value recieves from extras*/
		progressBackRe(extras.getBoolean(BackupActivity.KEY_ACTIVITY));
	
		}
		else
		{
			asyncthread.attach(this);
			adapter = asyncthread.getAdapter();
			listtask.setChoiceMode(2);
			listtask.setAdapter(adapter);
			upgradelistbar(asyncthread.point);
		}
		}	
		
	}
		
		/*Cancel clicklistener */
		cancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			
			finish();
			}
			});
		
	}
	
	private void progressBackRe(boolean checktask)
	{
		Uri allSystem = Settings.System.CONTENT_URI;
        Cursor c = managedQuery(allSystem, null, null, null, null);
        progress.setMax(listSys.size());
		if(checktask)
		{
			
			asyncthread=	new AsyncProcess(c,checktask,this);
			asyncthread.execute();
		}
		else
		{
			/*If is cloud download file in that */
			if(!_Cloud){
			SaveFile("data/data/com.ttc.mBackup/databases",
					DBAdapter.DATABASE_NAME,
					_Dir,
					_Name
					);
			}
			
			db.open();
			asyncthread=	new AsyncProcess(db.getAllValue(),checktask,this);
			asyncthread.execute();
			
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		// TODO Auto-generated method stub
		asyncthread.deattact();
		return asyncthread;
	}

	/*Backup Thread */
	private class AsyncProcess extends AsyncTask<Void,Bundle,Void>
	{
		PerformTask activity =null;
		Cursor sysset;
		Bundle data;
		boolean checktask;
		ArrayAdapter<String> adapter=null;
		int point =1;
		AsyncProcess(Cursor c,boolean checktask,PerformTask activity )
		{
			attach(activity);
			sysset = c;
			this.checktask=checktask;
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			
		/*
		 * checktaksk has boolean value, Backup is true - Restore is false ..
		 * When we choose task Restore, the db is opened above... We just read it 
		 * and write it to System Settings
		 * and Backuptask is choosen, we have to open db below here
		 * */
			//if(activity==null){
		if(checktask)
		{
			db.open();
		}
		/*
		 * Check null point
		 * */
		
			if((activity!=null)?sysset.move(point):sysset.moveToFirst())
			{ 
				/*
				 * Loop to get element from your database or get from systems
				 * */
				do
				{
					
					/*data, put value of System's name, value
					 * to put in to database file or restores....
					 *  */
					if(listSys.contains( sysset.getString(1))){
					data =new Bundle();
					data.putCharSequence("name", sysset.getString(1));
					data.putString("value", sysset.getString(2));
					
					/*Post messege to call  onProgressUpdate() and put data
					 * to get value into database or System Settings */
					publishProgress(data);
					try {
						
						/*Pause activity two second*/
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					}
			}while(sysset.moveToNext());
				/*Close database*/
				db.close();
				
				
			}
		
			
			
			/*
			 * Checktask : Backup - we have to database file to location which we chose
			 * and delete file database create default in App internal folder 
			 * Second If check if choose cloud method
			 * */
			if(checktask){
				if(!_Cloud){
			SaveFile(_Dir,
					_Name,
					"data/data/com.ttc.mBackup/databases",
					DBAdapter.DATABASE_NAME);}
			}
			
			/*Return resutl for BarSelector() Activity*/
			Intent data = new Intent();
			data.putExtra("FILE_NAME", _Name);
			data.putExtra("BACKUP", true);
			setResult(RESULT_OK,data);
			/*End this Activity*/
			finish();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			
			super.onPostExecute(result);
			
			
			
			
		}
		
		@Override
		protected void onProgressUpdate(Bundle... values) {
			// TODO Auto-generated method stub
			/*
			 * Checktask :
			 * - Backup : true --> insert value of System Setting in to database
			 * -Restore : false --> read database and put it into System Settings
			 * */
			if(activity==null)
			{
				Log.v("AsyncTask-PerformTask", "Skip it ");
			}
			else{
		if(checktask){	
		
		db.InsertSystem(values[0].getString("name"), 
					values[0].getString("value"));
		}
		else
			
		{  
			android.provider.Settings.System.putString(getContentResolver(),
				values[0].getString("name") ,
				values[0].getString("value"));
		
		}
		/*Set model and notify Adapter Change  to show in listview*/
		adapter=(ArrayAdapter<String>) listtask.getAdapter();
		adapter.add(values[0].getString("name"));
		/*check item when it backup or restore successfully*/
	listtask.setItemChecked(point-1, true);
		
	activity.upgradelistbar(point);
	point+=1;
		}
			
			
		//	/*Increase values of processbar*/
			//progress.incrementProgressBy(1);
		}

		
		 void attach(PerformTask activity2) {
				// TODO Auto-generated method stub
				this.activity=activity2;
			 }
		 
			void deattact()
			{activity=null;}
			
			int getProgress()
			{
				return point;
			}
			ArrayAdapter<String> getAdapter()
			{
				return adapter;
			}
}

	/*Update list and progressBar	*/
	void upgradelistbar(int _progress)
	{
		progress.setProgress(_progress);
	}
	
	/*Copy file for where you wanna backup*/
	private void SaveFile(String dst_dir, String name_dst,String src_dir, String name_src )
	{
		 	File dst = new File(dst_dir); 
	        File src = new File(src_dir);
	        File file_dst= new File(dst,name_dst);
	        File file_src = new File(src, name_src);
	       
	        /*Check file */
	        if(file_dst.exists())
	        {
	        	file_dst.delete();
	        }
	        
	        
	        
	        try {
	            // Make sure the Pictures directory exists.
	            ///File Doc
	            InputStream is = new FileInputStream(file_src);
	            //File ghi
	            OutputStream os = new FileOutputStream(file_dst);
	            byte[] data = new byte[is.available()];
	            is.read(data);
	            os.write(data);
	            is.close();
	            os.close();
	        } catch (IOException e) {
	            // Unable to create file, likely because external storage is
	            // not currently mounted.
	            Log.w("ExternalStorage", "Error writing " + file_src, e);
	        }
	        
	       
	    
	}
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_BACK)
		{
			if(!checker){
				//	Toast.makeText(getBaseContext(),"Cancel",Toast.LENGTH_LONG).show();
					asyncthread.cancel(true);
					Intent data = new Intent();
					setResult(RESULT_CANCELED,data);
					
				}
			finish();
			return true;
		}
		return false;
			
	}



}

